#/bin/sh

if [[ $1 == prod ]];then
  env=prod
  username=bbt_jd_pro
  password=bbt_jd_pro_2019
  dbName=bbt_jd_pro
elif [[ $1 == test ]];then
  env=test
  username=bbt_jd_dev
  password=bbt_jd_dev_2019
  dbName=bbt_jd_dev
else
  echo "参数输入有误，正确的格式为>>> sh $0  sh $0 [test|prod]"
  exit
fi
drdsIp=39.98.3.167

table=bbt_jd_member
outdir=$(pwd)/${env}
mkdir -p ${outdir}
drdsLog=${env}-drds.log
importSh=${env}-mysql-import.sh
importLog=${env}-mysql-import.log

echo "正在删除历史生产的数据..."
echo "rm -rf ${outdir}" || sh

echo "初始化日志+导入文件"
echo "#/bin/sh" > ${importSh}
echo "importLog=${importLog}" >>${importSh}
echo 'echo "" > ${importLog}' >> ${importSh}
echo "" > ${drdsLog}


function replaceFile(){
inFile=$1
outFile=$2
shopId=$3
nick=$4
cat ${inFile} | while read line
#for line in `cat ${inFile}`
do
	if [[ ! "$line" =~ ^INSERT.* ]]; then
    		echo "异常数据:$line"
		continue;
	fi

       tmpLine=${line//'${nick}'/'${shopId}'}
       insertOrUpdateSql=$(java -jar /bbtjd/bbt-data-member.jar "${tmpLine}" "0" "0,1,3")
        if [[ "$insertOrUpdateSql" =~ ^INSERT.* ]]; then
              echo "${insertOrUpdateSql}" >> ${outFile}
	else
	      echo "java转换异常:$insertOrUpdateSql"
        fi    
done
}


echo "即将遍历文件名称..."
fileNames=$(ls ./ | grep -e 'sql$')
for tmpFile in $fileNames
do
	echo "正在处理文件$tmpFile"
	arrName=(${tmpFile//[#.]/ })
	if (( ${#arrName[@]} != 3 ));then
             echo   "异常文件$tmpFile,实际长度是${#arrName[@]}"
             continue
        fi
	 
        tmpShopId=${arrName[0]}
        tmpNick=${arrName[1]}

	outFile=${outdir}/${table}#${tmpFile}
	echo "" > ${outFile}	
	
	replaceFile ${tmpFile} ${outFile} ${tmpNick} ${tmpShopId} 


	echo 'startTimeCmd=$(date +%s)' >>${importSh}
        echo "mysql -h ${drdsIp} -u${username} -p${password} ${dbName}  <${outFile};" >>${importSh}
        echo 'endTimeCmd=$(date +%s)'  >>${importSh}
        echo "echo '${outFile}' >>${importLog}" >>${importSh}
        echo 'echo "结束t=${endTimeCmd},开始t=${startTimeCmd},耗时=$(expr ${endTimeCmd} - ${startTimeCmd})" >> ${importLog}' >>${importSh}

done
